package com.lemeng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lemeng.service.AdService;
import com.lemeng.service.CategoryService;
import com.lemeng.service.SearchService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;
import java.util.TreeMap;

@Controller
public class SearchController {
   @Reference
    SearchService searchService;

    @GetMapping("search")
    public String index(Model model,@RequestParam Map<String,String> searchMap)throws  Exception{
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);
        if (!searchMap.containsKey("page")){
            searchMap.put("page","1");
        }

        TreeMap<String, String> treeMap = new TreeMap<>();
        for (String s : searchMap.keySet()) {
            treeMap.put(s,searchMap.get(s));
        }
        String url = "/search.do?";

        for (String key : treeMap.keySet()) {
            url=url+ "&" + key + "=" +treeMap.get(key);
        }

        Map search = searchService.search(searchMap);
        //总条数
        int total = (int)Long.parseLong(search.get("total").toString());
        int page = Integer.parseInt(searchMap.get("page"));
        int size = 5;
        int pages = total%size==0?total/size:(total/size+1);

        int start = 0;
        int end = 0;

        if (page<=3){
            start = 1;
            end = 5;
        }else if (page>=pages-2){
            start = pages-4;
            end = pages;
        }else {
            start = page-2;
            end = page+2;
        }

        if (start<1){
            start = 1;
        }
        if (end>pages){
            end = pages;
        }


        model.addAttribute("page",page);
        model.addAttribute("pages",pages);
        model.addAttribute("start",start);
        model.addAttribute("end",end);

        model.addAttribute("result",search);
        model.addAttribute("url",url);
        model.addAttribute("searchMap",searchMap);
        return "search";
    }



}
